/*
 * Copyright 2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import * as _ from "lodash"
import httpClient from "../httpclient"

export * from "./methods"

export enum PaymentMethod {
  AliPay = "alipay", WECHAT_PAY = "wechat_pay"
}

export enum PaymentStatus {

}

export class PaymentInstrument {
  public type: PaymentMethod
}

export class PaymentOrder {
  public id: string
}

export class Payment {
  public id: string
  public instrument: PaymentInstrument
  private total_amount: number
  private return_url: string
  public status: PaymentStatus
  public orders: PaymentOrder[] = []

  public get totalAmount() {
    return this.total_amount
  }

  public set totalAmount(totalAmount) {
    this.total_amount = totalAmount
  }

  public get returnUrl() {
    return this.return_url
  }

  public set returnUrl(returnUrl) {
    this.return_url = returnUrl
  }
}

export class PaymentServiceV1 {

  public static createPayment(payment: Payment): Promise<Payment> {
    return httpClient.post("/v1/payments", payment)
      .then(({ data }) => _.assign(new Payment(), data))
  }

  public static getPayment(id: string): Promise<Payment> {
    return httpClient.get(`/v1/payments/${id}`).then(({ data }) => _.assign(new Payment(), data))
  }

  public static getPaymentRedirectUrl(id: string): Promise<string> {
    return httpClient.get(`/v1/payments/${id}/redirect-url`).then(({ data }) => data)
  }

  public static redirectPayment(id: string): string {
    return `${httpClient.defaults.baseURL}/v1/payments/${id}/redirect`
  }

  public static savePayment(payment: Payment): Promise<void> {
    return httpClient.patch(`/v1/payments/${payment.id}`, payment)
  }
}
